import { useLatest } from 'ahooks';
import { useLayoutEffect } from 'react';

import { unref } from '../utils/unref';

/**
 * 监听元素尺寸变化
 */
export function useResizeObserver(
  callback: (result: DOMRect) => void,
  target: MaybeRef<HTMLElement | null | undefined>
): void {
  const targetEl = unref(target);
  const callbackRef = useLatest(callback);

  useLayoutEffect(() => {
    if (targetEl) {
      const update = () => callbackRef.current(targetEl.getBoundingClientRect());

      update();

      const observer = new window.ResizeObserver(update);

      observer.observe(targetEl);

      return () => observer.disconnect();
    }
  }, [targetEl]);
}
